﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;
using System.ComponentModel;

namespace DroughtAnalysis
{
    public static class RScriptRunner
    {
        /// <summary>
        /// Executes the generated R-script by calling RScript.exe
        /// </summary>
        /// <param name="pathToR">The path to R.exe</param>
        /// <param name="scriptFileName">the R-script full path</param>
        public static void ExecuteRScript(string pathToR, string scriptFileName, IList<DroughtSiteInfo> stationInfoList,
            BackgroundWorker worker, DoWorkEventArgs e)
        {
            worker.ReportProgress(0,"Executing R Script..");
            
            // checking input arguments
            var calculationResult = new RScriptCalculationResult();
            if (scriptFileName == null)
            {
                calculationResult.ErrorMessage = ("The R script file '" + scriptFileName + "' was not found. Cannot calculate drought analysis.");
                calculationResult.IsSuccessful = false;
                return;
            }
            if (!File.Exists(scriptFileName))
            {
                calculationResult.ErrorMessage = ("The R script file '" + scriptFileName + "' was not found. Cannot calculate drought analysis.");
                calculationResult.IsSuccessful = false;
                return;
            }
            
            string rScriptExe = Path.Combine(Path.GetDirectoryName(pathToR), "RScript.exe");
            ProcessStartInfo rScriptInfo = new ProcessStartInfo(rScriptExe);

            //rScriptInfo.UseShellExecute = false; //to allow standard error
            //rScriptInfo.RedirectStandardError = true;
           
            //the only argument passed to RSCRIPT.exe is the script file name.
            rScriptInfo.Arguments = String.Format(@"""{0}""", scriptFileName);

            string stderr = String.Empty;
            try
            {
                //starting RSCRIPT.exe as a process
                using (Process p = Process.Start(rScriptInfo))
                {
                    //stderr = p.StandardError.ReadToEnd(); //catch possible error in script

                    p.WaitForExit();
                }
                //calculation result is valid
                if (!string.IsNullOrEmpty(stderr))
                {
                    calculationResult.IsSuccessful = false;
                    calculationResult.ErrorMessage = " R Script Error: " + stderr;
                }
                else
                {
                    calculationResult.IsSuccessful = true;
                    calculationResult.ErrorMessage = String.Empty;
                    calculationResult.DroughtStationList = stationInfoList;
                }
            }
            catch (Exception ex)
            {
                calculationResult.IsSuccessful = false;
                calculationResult.ErrorMessage = ex.Message;
                if (!String.IsNullOrEmpty(stderr))
                {
                    calculationResult.ErrorMessage += " R Script Error: " + stderr;
                }
            }
            //return the result
            e.Result = calculationResult;

            //TODO: check for which station drought text files exist
        }
    }
}
